AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include("shared.lua")
resource.AddFile("models/bomb/bomb.mdl")
resource.AddFile("materials/models/bomb/bomb.vtf")
resource.AddFile("materials/models/bomb/bomb.vmt")
resource.AddFile("models/rocket/rocket.mdl")
resource.AddFile("materials/models/rocket/rocket.vtf")
resource.AddFile("materials/models/rocket/rocket.vmt")
util.PrecacheModel("models/bomb/bomb.mdl")
util.PrecacheModel("models/rocket/rocket.mdl")

function ConvertTime( time )//Formats Ime in Seconds
        mins = math.floor(time/60)
        secs = time-(mins*60)
        if(secs < 10) then // Adds 0 for second amounts below 10
                timeText = mins ..":0".. secs
        else
                timeText = mins ..":".. secs
        end
        return timeText
end

function Godmode(ply)
        if ply:GetVehicle():IsValid() then
                ply:SetTeam(4)
                ply.i = ply.i+1
                ply:PrintMessage(HUD_PRINTCENTER ,"Jesus for ".. (ply.looptimes-ply.i) .." seconds.")
                if(ply.i == ply.looptimes)then
                        ply.i = 0
                        ply:PrintMessage(HUD_PRINTCENTER ,"")
                        ply:SetTeam(3)
                        ply:GetVehicle():SetCollisionGroup( COLLISION_GROUP_NONE )
                end
        end
end

function GM:ReachedCheckpoint( ply , cpnumber , title )
        if ply:IsPlayer() && cpnumber == (ply.Checkpoint+1) && ply:GetVehicle():IsValid() then
                ply.Checkpoint = cpnumber
                local Jeep = ply:GetVehicle()
                ply.CheckAngles = Jeep:GetAngles() // Gets respawn angle
                if GetCPNum(cpnumber+1) == nil then
                        diff = os.difftime(os.time(), ply.StartTime)
                        Frags = ply:Frags()+1
                        ply:SetFrags(Frags) //Sets Lap number in score board
                        ply.Checkpoint = -1 //Back to start of lap
                        ply.totaltime = diff+ply.totaltime
                        umsg.Start("setLaps", ply)
						umsg.Long(Laps:GetInt())  
						umsg.End()
                        ply:ChatPrint("Lap ".. ply:Frags() .." completed in ".. ConvertTime(diff) ..". Total: ".. ConvertTime(ply.totaltime))
                        ply.StartTime = os.time()//Resets lap time
                        if (Frags == Laps:GetInt()) then
                                ply.wins = ply.wins+1
                                for k,v in pairs(player.GetAll()) do
                                        v:PrintMessage(HUD_PRINTCENTER,ply:Nick() .." has won the race in ".. ConvertTime(ply.totaltime) ..".")
                                        v:PrintMessage(HUD_PRINTTALK,ply:Nick() .." has won the race in ".. ConvertTime(ply.totaltime) ..".")
                                        if(v:Team() != 5)then
                                                v:Kill()
                                        end
                                        timer.Create("queueTimer", Inter:GetInt(), 1, QueuePlay)
                                end
                        end
                end
        end
end

function GetCPNum( cpid )
        cps = ents.FindByClass("checkpoint")
        for k, v in pairs(cps) do
                if v:GetNumber() == cpid then
                        return v:GetNumber() //Checks if contol point exsist
                end
        end
end

function GetCPPos( cpid )
        cps = ents.FindByClass("checkpoint_spawn")
        for k, v in pairs(cps) do
                if v:GetNumber() == cpid then
                        return v:GetPos() //Gets contol points spawns pos
                end
        end
end

function ResetPlayer( ply )
        ply.looptimes = RespawnTime:GetInt()
        ply.totaltime = 0
        ply.i = 0
        ply:SetDeaths( 0 ) //Reset deaths
        ply.Checkpoint = -1 //Set Checkpoint to first
        ply:SetFrags( 0 )//Set Laps to 0
        ply.CheckAngles = Angle(0, 0, 0)
end

function GM:PlayerSpawn(ply)
        if !ply.Checkpoint then
                umsg.Start("call_vgui_helpmenu", ply)
                umsg.End()
                ply.wins = 0
				ply.Queue = false
        end
		umsg.Start("setLaps", ply)
		umsg.Long(Laps:GetInt())  
		umsg.End()
        ply:SetTeam(5)
        ply.StartTime = os.time()
        ResetPlayer(ply)
        // Check for admins
        if ply:IsAdmin() then
                ply:Give("weapon_physgun")
				ply:Give("weapon_missle_launcher")
                ply:SetModel( "models/player/police.mdl" )
        else
                ply:StripWeapons()
                ply:SetModel( "models/player/kleiner.mdl" )
        end
		ply.LastBomb = 0
		ply.LastMissle = 0
end

function GM:PlayerNoClip(ply)
        if (ply:IsAdmin() || Noclip:GetBool()) then//Check Noclip
				if (ply:GetMoveType() == MOVETYPE_NOCLIP) then
					ply:GodDisable()
				else
					ply:GodEnable()
				end
				return true;
        else
                ply:ChatPrint("Only Admins Can Use Noclip") //Throw error to chat when not admin
                return false;
        end
end
function GM:ShowTeam(ply)
        umsg.Start("call_vgui_game", ply)
        umsg.End()
end
function GM:ShowSpare2(ply)
        umsg.Start("call_vgui_helpmenu", ply)
        umsg.End()
end

function GM:ShowHelp(ply)
        if ply:Alive( ) then
                if(ply:Team() != 4)then
                        if ply:GetVehicle():IsValid() then//Reset car or spawn car?
                                local Jeep = ply:GetVehicle()
                                local point = ply.Checkpoint
                                if(point == -1)then//If start go to finish line
                                        cps = ents.FindByClass("checkpoint_spawn")
                                        for k, v in pairs(cps) do
                                                point = point+1
                                        end
                                end
                                Jeep:SetPos((GetCPPos(point))+Vector(0,0,400))//Tele car to last check point
                                Jeep:SetVelocity(Vector(0,0,0))//Stop car
                                Jeep:SetAngles(ply.CheckAngles)//Set car to captured angle
								Jeep:SetPos((GetCPPos(point)))
                                ply:PrintMessage(HUD_PRINTCENTER ,"Jesus for ".. ply.looptimes .." seconds.")
                                time = "respawn".. ply:Nick() ..""
                                timer.Create( time, 1, ply.looptimes, Godmode, ply)
                                ply:GetVehicle():SetCollisionGroup( COLLISION_GROUP_WORLD )
                        else
                                if ply.Queue then
                                        ply.Queue = false
                                        ply:ChatPrint("You have been removed from queue!")
                                else
                                        ply.Queue = true
                                        ply:ChatPrint("You have been added to queue!")
                                end
                        end
                else
                        ply:ChatPrint("You are allready respawning!")
                end
        end
end

function GM:CanExitVehicle(ply)
        return false
end

function GM:PlayerDeath(ply) //Remove jeep on death
        local Jeep=ply:GetVehicle()
        SafeRemoveEntity(Jeep)
        ply:SetTeam(5)
end

function GM:PlayerDisconnected(ply) //Remove jeep on disconnect
        local Jeep=ply:GetVehicle()
        SafeRemoveEntity(Jeep)
        ply:SetTeam(5)
end

function QueuePlay()
        if qtime <= 0 then
				for k,v in pairs(ents.FindByClass("sent_bomb")) do
					v:Remove()
				end
				for k,v in pairs(ents.FindByClass("sent_missle")) do
					v:Remove()
				end
                for k, ply in pairs(team.GetPlayers(5)) do
                        if (ply.Queue) && (ply:Alive()) then
								ply:GodDisable()
								ply:SetMaxHealth(100)
								ply:SetHealth(ply:GetMaxHealth())
                                Jeep = ents.Create("prop_vehicle_jeep")
                                Jeep:SetModel("models/buggy.mdl")
                                Jeep:SetPos(Vector(0,0,0))
                                Jeep:SetKeyValue("vehiclescript","scripts/vehicles/jeep_test.txt")
                                Jeep:Spawn()
                                Jeep:Activate()
                                ply:EnterVehicle(Jeep) //Put player in jeep
                                ply.StartTime = os.time()//Set player start time
                                ResetPlayer( ply )
                                ply:PrintMessage(HUD_PRINTCENTER ,"Jesus for ".. ply.looptimes .." seconds.")
                                time = "respawn".. ply:Nick() ..""
                                timer.Create( time, 1, ply.looptimes, Godmode, ply)
                                ply:GetVehicle():SetCollisionGroup( COLLISION_GROUP_WORLD )
                                ply:SetTeam(3)
                                umsg.Start("setLaps", ply)
								umsg.Long(Laps:GetInt())  
								umsg.End()
                        end
                end
                timer.Simple(1, function()
                        timer.Destroy("queueTimer")
                        for k, v in pairs(player.GetAll()) do
							umsg.Start("setQueueTime", v)
							umsg.Long(-1)
							umsg.End() 
                        end
                end)
        end
        for k, v in pairs(player.GetAll()) do
                umsg.Start("setQueueTime", v)
				umsg.Long(qtime)  
				umsg.End()
        end
        qtime = qtime-1
end

function tick()
        if !(timer.IsTimer("queueTimer")) then
                b = true
                for k,v in pairs(team.GetPlayers(3)) do
                        b = false
                end
                for k,v in pairs(team.GetPlayers(4)) do
                        b = false
                end
                if b then
                        qtime = Inter:GetInt()
                        timer.Create("queueTimer", 1, (Inter:GetInt()+1), QueuePlay)
                end
        end
end

function GM:Initialize()
        RespawnTime =  CreateConVar( "rgm_respawntime", "3")
        Laps = CreateConVar( "rgm_laps", "3")
        Noclip = CreateConVar( "rgm_noclip", "0")
        WaitTime = CreateConVar( "rgm_mapstartwaittime", "30")
        Inter = CreateConVar( "rgm_intermission", "30")
        timer.Create("Tick", 1, 0, tick)
end

local delayBombs = 10 -- Delay of 20 seconds between each bombs

local function SpawnBomb(ply)

	if CurTime() < ply.LastBomb + delayBombs then return end -- A delay between bombs
	
	local jeep = ply:GetVehicle()
		
	if not ValidEntity(jeep) then return end -- Make sure that jeep is a valid entity, if not terminate execution
		
	local bomb = ents.Create("sent_bomb")
	bomb:SetPos( jeep:GetPos() + jeep:GetForward() * -160 + Vector(0,0,20) )
	bomb:Spawn()
	bomb:Activate()
	
	ply.LastBomb = CurTime()
end

local delayMissle = 4 -- Delay of 20 seconds between each bombs

local function SpawnMissle(ply)

	if CurTime() < ply.LastMissle + delayMissle then return end -- A delay between bombs
	
	local jeep = ply:GetVehicle()
		
	if not ValidEntity(jeep) then return end -- Make sure that jeep is a valid entity, if not terminate execution
	local sound = Sound("weapons/rpg/rocketfire1.wav")
	jeep:EmitSound( sound )
	local missle = ents.Create("sent_missle")
	missle:SetPos( jeep:GetPos() + jeep:GetForward() * 100 + Vector(0,0,12) )
	missle:SetAngles((jeep:GetAngles()+Vector(0,-90,0)))
	missle:Spawn()
	missle:Activate()
	missle:GetPhysicsObject():SetVelocity(jeep:GetForward() * 10000)
	ply.LastMissle = CurTime()
end

function GM:KeyPress(ply,key) -- You can easilly do the rest of your key detection here
	if key == IN_ATTACK2 then
		SpawnBomb(ply) -- If right click was pressed then we can call our SpawnBomb function for that player
	end
	if key == IN_ATTACK then
		SpawnMissle(ply)
	end
end

function killSilent(ply)
        ply:Kill();
end
concommand.Add( "killSilent", killSilent )